//
//  MJHttpUserAgentTool.m
//  MJ
//
//  Created by qiaoBu on 2017/12/12.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJHttpUserAgentTool.h"
#import "SAMKeychain.h"
#import "MJAppInfo.h"
#import "MJDeviceInfo.h"
#import "MJZlibTool.h"
#import "sys/utsname.h"


@implementation MJHttpUserAgentTool

+ (NSString *)getHttpUserAgent{
    
    //如果没有UUID，保存一个到钥匙串
    if ((![SAMKeychain passwordForService:[MJAppInfo appBundleID] account:MJ_UUID])||([[SAMKeychain passwordForService:[MJAppInfo appBundleID] account:MJ_UUID] isEqualToString:@""]))
    {
        //存储用户密码到钥匙串
        CFUUIDRef puuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
        NSString *uuid = [NSString stringWithFormat:@"%@", uuidString];
        NSString *appUUID = [NSString stringWithFormat:@"%@%@",[MJAppInfo appBundleID],uuid];
        //        TJLog(@"最新的uuid ------------ %@",uuid);
        [SAMKeychain setPassword:appUUID forService:[MJAppInfo appBundleID] account:MJ_UUID];
    }
    NSString *lastUuid = [SAMKeychain passwordForService:[MJAppInfo appBundleID] account:MJ_UUID];
    //    TJLog(@"lastUuid---:%@",lastUuid);
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    //http请求头
    NSString *headString = [NSString stringWithFormat:@"%@%@|%@|%@|%@|%@|%@",[MJAppInfo appAbbreviatedName],[MJAppInfo appBundleShortVersion],lastUuid,deviceString,[MJAppInfo appReleasedMarket],[MJAppInfo appReleasedStyle],[MJDeviceInfo deviceSystemVersion]];
    
    //    TJLog(@"headString---%@",headString);
    
    //1.转换为NSData
    NSData *headData = [headString dataUsingEncoding:NSUTF8StringEncoding];
    //2.进行zip压缩
    NSData *zipHeadData = [MJZlibTool zlibCompressData:headData];
    //3.删除多余的字节
    Byte cutByte[] = {120,156};
    NSData *cutData = [NSData dataWithBytes:cutByte length:2];
    
    NSRange range = {cutData.length,zipHeadData.length-cutData.length};
    NSData *headCutData = [zipHeadData subdataWithRange:range];
    
    //4.再进定义base64编码
    NSString *baseString = [headCutData base64EncodedStringWithOptions:0];
    
    
    //5.替换（得到最后的head头）
    baseString = [baseString stringByReplacingOccurrencesOfString:@"+" withString:@"("];
    baseString = [baseString stringByReplacingOccurrencesOfString:@"/" withString:@")"];
    baseString = [baseString stringByReplacingOccurrencesOfString:@"=" withString:@"@"];
    //    TJLog(@"login ---baseString ---------%@",baseString);
    // 存储User-Agent
    [[NSUserDefaults standardUserDefaults] setObject:baseString forKey:MJ_HttpUserAgent];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return baseString;
}


@end
